﻿using AutoMapper;
using DFGK_WMS.Context;
using DFGK_WMS.IRepository;
using DFGK_WMS.Model.DTO;
using DFGK_WMS.Model.Enum;
using DFGK_WMS.Model.Models;
using Microsoft.EntityFrameworkCore;
using NetTaste;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DFGK_WMS.Repository
{
    public class TReceivingOrderDetailRepository : BaseRepository<TReceivingOrderDetail>, ITReceivingOrderDetailRepository
    {
        private readonly IBarCodeRuleRepository _BarCodeRuleRepositoy;

        public TReceivingOrderDetailRepository(DFGK_DB context, IMapper mapper, IBarCodeRuleRepository barCodeRuleRepositoy) : base(context, mapper)
        {
            _BarCodeRuleRepositoy = barCodeRuleRepositoy;
        }

        /// <summary>
        /// 添加入库单管理
        /// </summary>
        /// <param name="m"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public bool AddTReceivingOrderDetail(List<ShelvesSinles> sList, out string message)
        {
            message = "";
            using (var tran = Context.Database.BeginTransaction())
                try
                {
                    #region 货主信息
                    //货主信息
                    //if (m.OwnerId.HasValue)
                    //{
                    //    var depobj = Context.TDepartments.AsQueryable();
                    //    var depowobj = Context.TDepartmentOwners.Where(x => x.OwnerId == m.OwnerId);
                    //    var owobj = Context.TOwners.Where(x=>x.Status==1);
                    //    var delist = (from d in depobj
                    //                  join de in depowobj
                    //                  on d.Id equals de.DepartmentId
                    //                  join o in owobj
                    //                  on de.OwnerId equals o.Id
                    //                  select d).FirstOrDefault();
                    //    if (delist != null)
                    //    {
                    //        m.DeptCode = delist.DepartmentCode;
                    //        m.DeptName = delist.DepartmentName;
                    //        var owerobj = owobj.Where(x => x.Id == m.OwnerId).FirstOrDefault();
                    //        if (owerobj != null)
                    //        {
                    //            m.OwnerName = owerobj.Name;
                    //        }
                    //    }
                    //    else
                    //    {
                    //        message = "货主不存在或已被禁用，请先维护";
                    //        return false;
                    //    }
                    //}
                    //else
                    //{
                    //    m.OwnerId = 0;
                    //    m.OwnerName = "";
                    //    m.DeptCode = "";
                    //    m.DeptName = "";
                    //}
                    #endregion

                    #region 库房信息
                    //库房信息
                    //var warehouseobj = Context.TWarehouses.Find(m.WarehouseId);
                    //if (warehouseobj != null && warehouseobj.Status==1)
                    //{
                    //    m.WarehouseName = warehouseobj.Name;
                    //    m.WarehouseCode = warehouseobj.Code;
                    //}
                    //else
                    //{
                    //    message = "仓库不存在或仓库已被禁用，请先维护";
                    //    return false;
                    //}
                    #endregion

                    #region 供应商信息
                    //供应商信息
                    //var supplierobj = Context.TSuppliers.Find(m.SupplierId);
                    //if (supplierobj != null)
                    //{
                    //    m.SupplierName = supplierobj.Name;
                    //}
                    #endregion

                    #region 物料批次
                    //物料批次
                    //TMaterialKey materialKey = null;
                    //var materkeyobj = Context.TMaterialKeys.FirstOrDefault(x => x.BatchNo == s.BatchNo && x.MaterialCode == s.MaterialNo);
                    //if (materkeyobj != null)
                    //{
                    //    materialKey = materkeyobj;
                    //}
                    #endregion

                    #region 逻辑分区
                    //逻辑分区
                    //var dicobj = Context.TDictItems.FirstOrDefault(x => x.ItemCode == m.LogicalPartCode);
                    //if (dicobj != null)
                    //{
                    //    m.LogicalPartName = dicobj.ItemName;
                    //}
                    #endregion

                    #region 订单来源默认手动创建
                    //订单来源默认手动创建
                    //m.SourceType = 0;
                    ////质检状态默认为合格
                    //m.QualityState = 1;
                    //m.ReceivedQty = 0;
                    //m.PackagedQty = 0;
                    //m.PackQty = 0;
                    #endregion

                    #region 审计字段
                    //m.CreateUserId = m.NowUserId;
                    //m.CreateUserName = m.NowUserRealName;
                    //m.CreateDate = DateTime.Now;
                    //m.ModifyUserId = m.NowUserId;
                    //m.ModifyUserName = m.NowUserRealName;
                    //m.ModifyDate = DateTime.Now;
                    //m.AuditUserId = m.NowUserId;
                    //m.AuditUserName = m.NowUserRealName;
                    //m.AuditDate = DateTime.Now;
                    //m.SubmitUserId = m.NowUserId;
                    //m.SubmitUserName = m.NowUserRealName;
                    //m.SubmitDate = DateTime.Now;
                    #endregion

                    #region 采购订单行项目类型
                    //采购订单行项目类型
                    //m.PurOrderLineType = 0;
                    //m.StackedQty = 0;
                    #endregion

                    #region 判断物料批次是否为空
                    //if (materialKey == null)
                    //{
                    //    TMaterialKey materkeyinsert = new TMaterialKey();
                    //    materkeyinsert.BatchNo = m.BatchNo;
                    //    materkeyinsert.MaterialId = m.MaterialId;
                    //    materkeyinsert.OutFactoryDate = m.OutFactoryDate;
                    //    materkeyinsert.OwnerId = m.OwnerId;
                    //    materkeyinsert.OwnerName = m.OwnerName;
                    //    materkeyinsert.ProduceFactory = m.ProduceFactory;
                    //    materkeyinsert.ProductDate = m.ProductDate;
                    //    materkeyinsert.Qadate = m.Qadate;
                    //    materkeyinsert.SupplierName = m.SupplierName;
                    //    materkeyinsert.SupplierId = m.SupplierId;
                    //    materkeyinsert.ExpireDate = m.ExpireDate;
                    //    materkeyinsert.CreateDate = DateTime.Now;
                    //    materkeyinsert.MaterialCode = m.MaterialCode;
                    //    materkeyinsert.MaterialName = m.MaterialName;
                    //    materkeyinsert.QualityState = m.QualityState;
                    //    materkeyinsert.DeptCode = m.DeptCode;
                    //    materkeyinsert.DeptName = m.DeptName;
                    //    materkeyinsert.Mblnr = m.Mblnr;
                    //    materkeyinsert.Mjahr = m.Mjahr;
                    //    materkeyinsert.Zeile = m.Zeile;
                    //    materkeyinsert.ContractNo = m.ContractNo;
                    //    materkeyinsert.PurOrderNo = m.PurOrderNo;
                    //    materkeyinsert.PurOrderLineNo = m.PurOrderLineNo;
                    //    materkeyinsert.PurOrderLineType = m.PurOrderLineType;
                    //    materkeyinsert.ProOrderNo = m.ProOrderNo;
                    //    materkeyinsert.OutOrderNo = m.OutOrderNo;
                    //    Context.TMaterialKeys.Add(materkeyinsert);
                    //    int result = Context.SaveChanges();
                    //    if (result == 0)
                    //    {
                    //        message = "保存失败！";
                    //        tran.Rollback();
                    //        return false;
                    //    }
                    //    m.MaterialKeyId = materkeyinsert.Id;
                    //}
                    //else
                    //{
                    //    m.MaterialKeyId = materialKey.Id;
                    //    var materkey = Context.TMaterialKeys.Find(m.MaterialKeyId);
                    //    if (materkey != null)
                    //    {
                    //        materkey.BatchNo = m.BatchNo;
                    //        materkey.OutFactoryDate = m.OutFactoryDate;
                    //        materkey.OwnerId = m.OwnerId;
                    //        materkey.OwnerName = m.OwnerName;
                    //        materkey.ProduceFactory = m.ProduceFactory;
                    //        materkey.ProductDate = m.ProductDate;
                    //        materkey.Qadate = m.Qadate;
                    //        materkey.SupplierId = m.SupplierId;
                    //        materkey.SupplierName = m.SupplierName;
                    //        materkey.ExpireDate = m.ExpireDate;
                    //        materkey.MaterialCode = m.MaterialCode;
                    //        materkey.MaterialName = m.MaterialName;
                    //        materkey.QualityState = m.QualityState;
                    //        materkey.DeptCode = m.DeptCode;
                    //        materkey.DeptName = m.DeptName;
                    //        materkey.Mblnr = m.Mblnr;
                    //        materkey.Mjahr = m.Mjahr;
                    //        materkey.Zeile = m.Zeile;
                    //        materkey.ContractNo = m.ContractNo;
                    //        materkey.ProOrderNo = m.ProOrderNo;
                    //        materkey.PurOrderLineNo = m.PurOrderLineNo;
                    //        materkey.PurOrderLineType = m.PurOrderLineType;
                    //        materkey.ProOrderNo = m.ProOrderNo;
                    //        materkey.OutOrderNo = m.OutOrderNo;
                    //        Context.TMaterialKeys.Update(materkey);
                    //    }
                    //    int result = Context.SaveChanges();
                    //    if (result <= 0)
                    //    {
                    //        message = "保存失败！";
                    //        tran.Rollback();
                    //        return false;
                    //    }
                    //}
                    #endregion


                    foreach (var s in sList)
                    {
                        #region 物料信息
                        //物料信息
                        var materialobj = Context.TMaterials.Where(x=>x.Code == s.MaterialNo);
                        if (materialobj == null)
                        {
                            message = $"不存在物料号为{s.MaterialNo}的物料信息";
                            return false;
                        }
                        //var material = materialobj.FirstOrDefault(x => x.BatchMark == s.BatchNo);
                        //if (material == null)
                        //{
                        //    message = $"不存在物料号为{s.MaterialNo}，批次号为{s.BatchNo}的物料信息";
                        //    return false;
                        //}
                        #endregion
                    }

                    //Context.TReceivingOrderDetails.Add(m);
                    int resultt = Context.SaveChanges();
                    if (resultt > 0)
                    {
                        tran.Commit();
                        return true;
                    }
                    tran.Rollback();
                    return false;

                }
                catch (Exception)
                {
                    tran.Rollback();
                    throw;
                }
        }

        /// <summary>
        /// 删除入库单
        /// </summary>
        /// <param name="rid"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public bool DelTReceivingOrderDetail(int rid)
        {
            var sobj = Context.TReceivingOrderDetails.Find(rid);
            if (sobj == null)
            {
                return false;
            }
            Context.TReceivingOrderDetails.Remove(sobj);
            return Context.SaveChanges() > 0;
        }

        /// <summary>
        /// 显示入库单
        /// </summary>
        /// <param name="billType"></param>
        /// <param name="status"></param>
        /// <param name="warehouseid"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="totalCount"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public List<TReceivingOrderDetail> GetReceivingOrderDetailList(DateTime? startTime, DateTime? endTime, string orderSn, int billType, int status, int warehouseid, int pageIndex, int pageSize, out int totalCount)
        {
            var list = Context.TReceivingOrderDetails.AsQueryable();
            //入库单号
            if (!string.IsNullOrEmpty(orderSn))
            {
                list = list.Where(x => x.OrderSn.Contains(orderSn));
            }

            if (billType != 0)
            {
                list = list.Where(x => x.BillType == billType);
            }

            if (status < 8)
            {
                list = list.Where(x => x.Status == status);
            }

            if (warehouseid != 0)
            {
                list = list.Where(x => x.WarehouseId == warehouseid);
            }

            if (warehouseid != 0)
            {
                list = list.Where(x => x.WarehouseId == warehouseid);
            }

            if (startTime != null && endTime != null)
                list = list.Where(s => s.CreateDate.Date >= startTime && s.CreateDate.Date <= endTime);

            totalCount = list.Count();

            list = list.OrderByDescending(x => x.CreateDate);

            return list.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
        }

        /// <summary>
        /// 查看
        /// </summary>
        /// <param name="rid"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public TReceivingOrderDetail GetTReceivingOrderDetailById(int rid)
        {
            return Context.TReceivingOrderDetails.Find(rid);
        }

        /// <summary>
        /// 修改入库单
        /// </summary>
        /// <param name="m"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public bool UpdTReceivingOrderDetail(TReceivingOrderDetail m, out string message)
        {
            message = "";
            using (var tran = Context.Database.BeginTransaction())
                try
                {
                    //货主信息
                    if (m.OwnerId.HasValue)
                    {
                        var depobj = Context.TDepartments.AsQueryable();
                        var depowobj = Context.TDepartmentOwners.Where(x => x.OwnerId == m.OwnerId);
                        var owobj = Context.TOwners.Where(x => x.Status == 1);
                        var delist = (from d in depobj
                                      join de in depowobj
                                      on d.Id equals de.DepartmentId
                                      join o in owobj
                                      on de.OwnerId equals o.Id
                                      select d).FirstOrDefault();
                        if (delist != null)
                        {
                            m.DeptCode = delist.DepartmentCode;
                            m.DeptName = delist.DepartmentName;
                            var owerobj = owobj.Where(x => x.Id == m.OwnerId).FirstOrDefault();
                            if (owerobj != null)
                            {
                                m.OwnerName = owerobj.Name;
                            }
                        }
                        else
                        {
                            message = "货主不存在或已被禁用，请先维护";
                            return false;
                        }
                    }
                    else
                    {
                        m.OwnerId = 0;
                        m.OwnerName = "";
                        m.DeptCode = "";
                        m.DeptName = "";
                    }

                    //库房信息
                    var warehouseobj = Context.TWarehouses.Find(m.WarehouseId);
                    if (warehouseobj != null && warehouseobj.Status==1)
                    {
                        m.WarehouseName = warehouseobj.Name;
                        m.WarehouseCode = warehouseobj.Code;
                    }
                    else
                    {
                        message = "仓库不存在或仓库已被禁用，请先维护";
                        return false;
                    }

                    //TReceivingOrderDetail oldData = null;
                    //var olddataobj = Context.TReceivingOrderDetails.Find(m.Id);
                    //if (olddataobj == null) 
                    //{
                    //    message = "当前数据可能已被删除，请刷新后再试";
                    //    return false;
                    //}
                    //else
                    //{
                    //    if(olddataobj.Status!=0)
                    //    {
                    //        message = "只有状态为创建的入库单才能修改";
                    //        return false;
                    //    }
                    //    oldData = olddataobj;
                    //}
                    //oldData = olddataobj;
                    //供应商信息
                    var supplierobj = Context.TSuppliers.Find(m.SupplierId);
                    if (supplierobj != null)
                    {
                        m.SupplierName = supplierobj.Name;
                    }
                    //物料信息
                    var materialobj = Context.TMaterials.Find(m.MaterialId);
                    if (materialobj != null)
                    {
                        m.MaterialCode = materialobj.Code;
                        m.MaterialImg = materialobj.Img;
                        m.MaterialName = materialobj.Name;
                        m.UnitId = materialobj.UnitId;
                        m.UnitName = materialobj.UnitName;
                        m.MaterialTypeCode = materialobj.TypeCode;
                        m.MaterialTypeName = materialobj.TypeName;
                        if (materialobj.ExpirationMonth.HasValue && m.ProductDate.HasValue)
                        {
                            m.ExpireDate = m.ProductDate.Value.AddMonths(materialobj.ExpirationMonth.Value);
                        }
                    }
                    //物料批次
                    TMaterialKey materialKey = null;
                    var materkeyobj = Context.TMaterialKeys.Find(m.MaterialKeyId);
                    if (materkeyobj == null)
                    {                     
                        var materkeyobj2 = Context.TMaterialKeys.FirstOrDefault(x => x.BatchNo == m.BatchNo && x.MaterialId == m.MaterialId);
                        if(materkeyobj2!=null)
                        {
                            materialKey = materkeyobj2;
                        }
                    }
                    else
                    {
                        materialKey = materkeyobj;
                    }
                    //逻辑分区
                    var dicobj = Context.TDictItems.FirstOrDefault(x => x.ItemCode == m.LogicalPartCode);
                    if (dicobj != null)
                    {
                        m.LogicalPartName = dicobj.ItemName;
                    }                

                    #region 审计字段
                    m.ModifyUserId = m.NowUserId;
                    m.ModifyUserName = m.NowUserRealName;
                    m.ModifyDate = DateTime.Now;
                    m.AuditUserId = m.NowUserId;
                    m.AuditUserName = m.NowUserRealName;
                    m.AuditDate = DateTime.Now;
                    #endregion                
                    if (materialKey == null)
                    {
                        TMaterialKey materkeyinsert = new TMaterialKey();
                        materkeyinsert.BatchNo = m.BatchNo;
                        materkeyinsert.MaterialId = m.MaterialId;
                        materkeyinsert.OutFactoryDate = m.OutFactoryDate;
                        materkeyinsert.OwnerId = m.OwnerId;
                        materkeyinsert.OwnerName = m.OwnerName;
                        materkeyinsert.ProduceFactory = m.ProduceFactory;
                        materkeyinsert.ProductDate = m.ProductDate;
                        materkeyinsert.Qadate = m.Qadate;
                        materkeyinsert.SupplierName = m.SupplierName;
                        materkeyinsert.SupplierId = m.SupplierId;
                        materkeyinsert.ExpireDate = m.ExpireDate;
                        materkeyinsert.CreateDate = DateTime.Now;
                        materkeyinsert.MaterialCode = m.MaterialCode;
                        materkeyinsert.MaterialName = m.MaterialName;
                        materkeyinsert.QualityState = m.QualityState;
                        materkeyinsert.DeptCode = m.DeptCode;
                        materkeyinsert.DeptName = m.DeptName;
                        materkeyinsert.Mblnr = m.Mblnr;
                        materkeyinsert.Mjahr = m.Mjahr;
                        materkeyinsert.Zeile = m.Zeile;
                        materkeyinsert.ContractNo = m.ContractNo;
                        materkeyinsert.PurOrderNo = m.PurOrderNo;
                        materkeyinsert.PurOrderLineNo = m.PurOrderLineNo;
                        materkeyinsert.PurOrderLineType = m.PurOrderLineType;
                        materkeyinsert.ProOrderNo = m.ProOrderNo;
                        materkeyinsert.OutOrderNo = m.OutOrderNo;
                        Context.TMaterialKeys.Add(materkeyinsert);
                        int result = Context.SaveChanges();
                        if (result == 0)
                        {
                            message = "保存失败！";
                            tran.Rollback();
                            return false;
                        }
                        m.MaterialKeyId = materkeyinsert.Id;
                    }
                    else
                    {
                        m.MaterialKeyId = materialKey.Id;
                        var materkey = Context.TMaterialKeys.Find(m.MaterialKeyId);
                        if (materkey != null)
                        {
                            materkey.BatchNo = m.BatchNo;
                            materkey.OutFactoryDate = m.OutFactoryDate;
                            materkey.OwnerId = m.OwnerId;
                            materkey.OwnerName = m.OwnerName;
                            materkey.ProduceFactory = m.ProduceFactory;
                            materkey.ProductDate = m.ProductDate;
                            materkey.Qadate = m.Qadate;
                            materkey.SupplierId = m.SupplierId;
                            materkey.SupplierName = m.SupplierName;
                            materkey.ExpireDate = m.ExpireDate;
                            materkey.MaterialCode = m.MaterialCode;
                            materkey.MaterialName = m.MaterialName;
                            materkey.QualityState = m.QualityState;
                            materkey.DeptCode = m.DeptCode;
                            materkey.DeptName = m.DeptName;
                            materkey.Mblnr = m.Mblnr;
                            materkey.Mjahr = m.Mjahr;
                            materkey.Zeile = m.Zeile;
                            materkey.ContractNo = m.ContractNo;
                            materkey.ProOrderNo = m.ProOrderNo;
                            materkey.PurOrderLineNo = m.PurOrderLineNo;
                            materkey.PurOrderLineType = m.PurOrderLineType;
                            materkey.ProOrderNo = m.ProOrderNo;
                            materkey.OutOrderNo = m.OutOrderNo;
                            Context.TMaterialKeys.Update(materkey);
                        }
                        int result = Context.SaveChanges();
                        if (result <= 0)
                        {
                            message = "保存失败！";
                            tran.Rollback();
                            return false;
                        }
                    }
                    Context.TReceivingOrderDetails.Update(m);
                    int resultt = Context.SaveChanges();
                    if (resultt > 0)
                    {
                        tran.Commit();
                        return true;
                    }
                    tran.Rollback();
                    return false;

                }
                catch (Exception)
                {
                    tran.Rollback();
                    throw;
                }
        }

        /// <summary>
        /// 修改状态
        /// </summary>
        /// <param name="m"></param>
        /// <returns></returns>
        public bool UpdTReceivingOrderDetaState(ReceivingOrderDetailDto m)
        {
            var robj = Context.TReceivingOrderDetails.Find(m.Id);

            if (robj != null)
            {

                switch (robj.Status)
                {
                    case 0:
                        var uobj = Context.TUsers.FirstOrDefault(x => x.Id == m.NowUserId && x.JobNo == m.JobNo);
                        if (uobj != null)
                        {
                            robj.SubmitUserId = m.NowUserId;
                            robj.SubmitUserName = m.NowUserRealName;
                            robj.SubmitDate = DateTime.Now;
                            robj.Remark = m.Remark;
                            //修改为：审核通过
                            robj.Status = 2;
                            Context.TReceivingOrderDetails.Update(robj);
                            break;
                        }
                        return false;

                    case 1:
                        break;

                    case 2:
                        robj.ModifyUserId = m.NowUserId;
                        robj.ModifyUserName = m.NowUserRealName;
                        robj.ModifyDate = DateTime.Now;
                        //修改为：作业中
                        robj.Status = 3;
                        Context.TReceivingOrderDetails.Update(robj);
                        break;

                    case 3:
                        robj.ModifyUserId = m.NowUserId;
                        robj.ModifyUserName = m.NowUserRealName;
                        robj.ModifyDate = DateTime.Now;
                        //修改为：已完成
                        robj.Status = 4;
                        Context.TReceivingOrderDetails.Update(robj);
                        break;

                    default:
                        break;
                }
                return Context.SaveChanges() > 0;
            }
            return false;
        }

        /// <summary>
        /// 导出入库单
        /// </summary>
        /// <returns></returns>
        public List<TReceivingOrderDetail> GetTReceivingOrderDetailExcel()
        {
            try
            {
                return Context.TReceivingOrderDetails.AsQueryable().ToList();
            }
            catch (Exception)
            {

                throw;
            }
        }

        /// <summary>
        /// 执行入库作业
        /// </summary>
        /// <returns></returns>
        public bool ExecReceving(TReceivingOrderDetail detail, out string errMsg)
        {

            errMsg = string.Empty;
            TReceivingOrderDetail? orderDetail = detail;

            if (orderDetail.Status != (int)EmBillStatus.Pass)
            {
                // throw new Exception("入库单不存在");
                errMsg = "入库单未审核通过";
                return false;
            }

            orderDetail.Status = (int)EmBillStatus.Executing;
            orderDetail.ModifyDate = DateTime.Now;
            // orderDetail.ModifyUserId = 0;
            // orderDetail.ModifyUserName = "";

            bool result = base.Upd(orderDetail);

            return result;
        }

        /// <summary>
        /// 创建入库单
        /// </summary>
        /// <returns></returns>
        public bool AddTReceivingOrderDetail(int receivingBillDetailId, decimal qty, out string errMsg)
        {
            errMsg = string.Empty;
            TReceivingOrderDetail orderDetail = new TReceivingOrderDetail();

            TReceivingBill? receivingBill = Context.TReceivingBills.Find(receivingBillDetailId);
            TReceivingBillDetail? billDetail = Context.TReceivingBillDetails.FirstOrDefault(it => it.BillId == receivingBill.Id);
            orderDetail.OrderSn = _BarCodeRuleRepositoy.GetBarCodeSample(1);
            orderDetail.BatchNo = billDetail.BatchNo;
            orderDetail.BillType = (int)EmInBillType.NormalIn;
            orderDetail.MaterialId = billDetail.MaterialId;
            orderDetail.Qty = qty;
            orderDetail.QualityState = 1;
            orderDetail.Status = 3;
            orderDetail.SourceType = 1;

            //默认通用仓储分区
            orderDetail.LogicalPartCode = "";
            orderDetail.LogicalPartName = "";
            orderDetail.OwnerId = billDetail.OwnerId;
            orderDetail.OwnerName = billDetail.OwnerName;
            orderDetail.WarehouseId = receivingBill.WarehouseId;
            orderDetail.SupplierId = receivingBill.SupplierId;
            orderDetail.SupplierName = receivingBill.SupplierName;
            orderDetail.PurOrderNo = receivingBill.BillNo;
            orderDetail.PurOrderLineNo = receivingBill.BillNo + receivingBill.Id.ToString();
            orderDetail.ReceivingBillDetailId = billDetail.Id;
            orderDetail.ReceivingBillId = receivingBill.Id;
            orderDetail.ProductDate = billDetail.ProductDate;
            orderDetail.ProduceFactory = billDetail.ProduceFactory;
            orderDetail.OutFactoryDate = billDetail.OutFactoryDate;
            orderDetail.ExpireDate = billDetail.ExpireDate;
            orderDetail.BatchNoExplain = billDetail.BatchNoExplain;
            orderDetail.Price = billDetail.Price;
            if (billDetail.Price > 0)
            {
                orderDetail.TotalPrice = billDetail.Price * billDetail.Qty; ;
            }
            orderDetail.CreateDate = DateTime.Now;
            orderDetail.CreateUserId = 0;
            orderDetail.CreateUserName = "";

            TWarehouse? warehouse = Context.TWarehouses.FirstOrDefault(it => it.Id == receivingBill.WarehouseId);
            if (warehouse == null)
            {
                errMsg = "仓库Id【" + orderDetail.Id + "】不存在，请先维护";
                return false;
            }
            orderDetail.WarehouseCode = warehouse.Code;//仓库
            orderDetail.WarehouseName = warehouse.Name;//名称

            TMaterial? material = Context.TMaterials.FirstOrDefault(it => it.Id == orderDetail.MaterialId);
            if (material != null)
            {
                orderDetail.MaterialImg = material.Img;
                orderDetail.MaterialName = material.Name;
                orderDetail.MaterialCode = material.Code;
                orderDetail.MaterialTypeCode = material.TypeCode;
                orderDetail.MaterialTypeName = material.TypeName;
                orderDetail.UnitId = material.UnitId;
                orderDetail.UnitName = material.UnitName;
                if (material.ExpirationMonth.HasValue && orderDetail.ProductDate.HasValue)
                {
                    orderDetail.ExpireDate = orderDetail.ProductDate.Value.AddMonths(material.ExpirationMonth.Value);
                }
            }
            TMaterialKey? materialKey = Context.TMaterialKeys.FirstOrDefault(it => it.BatchNo == orderDetail.BatchNo && it.MaterialId == material.Id);


            using var transaction = Context.Database.BeginTransaction();
            if (materialKey == null)
            {
                materialKey = new TMaterialKey()
                {
                    BatchNo = orderDetail.BatchNo,
                    MaterialId = orderDetail.MaterialId,
                    OutFactoryDate = orderDetail.OutFactoryDate,
                    OwnerId = orderDetail.OwnerId,
                    OwnerName = orderDetail.OwnerName,
                    ProduceFactory = orderDetail.ProduceFactory,
                    ProductDate = orderDetail.ProductDate,
                    //    QADate = model.QADate,
                    SupplierId = orderDetail.SupplierId,
                    SupplierName = orderDetail.SupplierName,
                    WarehouseId = warehouse.Id,//仓库
                    WarehouseCode = warehouse.Code,//仓库
                    WarehouseName = warehouse.Name,//名称
                    ExpireDate = orderDetail.ExpireDate,
                    CreateDate = DateTime.Now,
                    MaterialCode = orderDetail.MaterialCode,
                    MaterialName = orderDetail.MaterialName,
                    //    QualityState = model.QualityState,
                    DeptCode = orderDetail.DeptCode,
                    DeptName = orderDetail.DeptName,
                    Mblnr = orderDetail.Mblnr,
                    Mjahr = orderDetail.Mjahr,
                    Zeile = orderDetail.Zeile,
                    ContractNo = orderDetail.ContractNo,
                    PurOrderNo = orderDetail.PurOrderNo,
                    PurOrderLineNo = orderDetail.PurOrderLineNo,
                    PurOrderLineType = orderDetail.PurOrderLineType,
                    ProOrderNo = orderDetail.ProOrderNo,
                    OutOrderNo = orderDetail.OutOrderNo
                };

                Context.TMaterialKeys.Add(materialKey);
                Context.SaveChanges();
                if (materialKey.Id == 0)
                {
                    errMsg = "保存失败";
                    Context.Database.RollbackTransaction();
                    return false;
                }
            }
            else
            {
                orderDetail.MaterialKeyId = materialKey.Id;
            }
            Context.TReceivingOrderDetails.Add(orderDetail);
            if (Context.SaveChanges() == 0)
            {
                errMsg = "保存失败";
                Context.Database.RollbackTransaction();
                return false;
            }

            decimal? recQty = Context.TReceivingBills.Find(receivingBillDetailId)?.ReceivedQTY;
            recQty += qty;

            Context.TReceivingBills.Update(new TReceivingBill
            {
                Id = receivingBillDetailId,
                Status = 1,//已收货
                ReceivedQTY = recQty
            });

            if (Context.SaveChanges() == 0)
            {
                errMsg = "保存失败";
                Context.Database.RollbackTransaction();
                return false;

            }
            transaction.Commit();

            return true;
        }
    }
}
